/**
 * @description jobs
 *
 * @author xiaomi
 */

// env
require('../env');

// deps
const kue = require('./kue-shim');
const logger = require('../app/services/logger');
const schedule = require('node-schedule');

// all processer
const processers = [
    // require('./app-push'),
    // require('./sendmail'),
    // require('./schedule')
];

// queue
const queue = kue.createQueue({
    redis: process.env.REDIS_URL
});

// error report
queue.on('error', err => {
    logger.error(err, err.data);
});

// Run as a server
if(require.main === module) {
    // Global error handle
    process.once('uncaughtException', err => {
        logger.error(err);

        queue.shutdown(1000, err => {
            console.error('Kue shutdown result: ', err || 'OK');

            process.exit(1);
        });
    });

    // Init processer
    processers.forEach(processer => {
        processer(queue);
    });

    // Init schedule tasks
    // const scheduleTasks = require('./schedule-tasks');
    // scheduleTasks.forEach(scheduleTask => {
    //     schedule.scheduleJob(scheduleTask.interval, (...args) => {
    //         scheduleTask.handler(queue, ...args);
    //     });
    // });

    const pkgs = require('../package.json');
    const JOBS_HOST = process.env.JOBS_HOST;
    const JOBS_PORT = process.env.JOBS_PORT;

    kue.app.set('title', `Kue - ${pkgs.name}`);
    kue.app.listen(JOBS_PORT, '127.0.0.1');

    logger.info('Jobs server start...', {
        host: 'http://' + JOBS_HOST,
        port: JOBS_PORT
    });
}

// assign queue.processers
queue.processers = processers;

module.exports = queue;
